package com.haiyou.email.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

/**
 * 下载工具类
 *
 * @author huangzl
 */
@Slf4j
public class DownloadUtil {

    public static String downloadFromUrl(String url, String savePath) {
        try {
            log.info("url文件------>{}", url);
            URL httpUrl = new URL(url);
            String filePath = savePath(url, savePath);
            log.info("文件保存路径------>{}", filePath);
            File f = new File(filePath);
            FileUtils.copyURLToFile(httpUrl, f);
            return filePath;
        } catch (Exception e) {
            log.error("文件下载失败----->{}", e.getMessage());
            return null;
        }
    }

    public static String savePath(String url, String savePath) throws UnsupportedEncodingException {
        String dirPath = uploadPath(savePath);
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        int index = url.lastIndexOf("/");
        return dirPath + URLDecoder.decode(url.substring(index + 1), "UTF-8");
    }

    /**
     * 上传附件目录
     *
     * @return
     */
    public static String uploadPath(String savePath) {
        savePath = StringUtils.isEmpty(savePath) ? "uploadFiles" : savePath;
        String path = System.getProperty("user.dir");
        String dirPath = path + File.separator + savePath + File.separator;
        return dirPath;
    }

}
